//
//  searchStockViewController.swift
//  股票框架
//
//  Created by 李小骥 on 2017/9/29.
//  Copyright © 2017年 李小骥. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class SearchStockViewController: UIViewController,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating {
    let cellID = "SearchStockCell"
    weak var marketViewControllerDelegate:MarketViewController!
    var searchBar=UISearchBar()
//    var searchBar=UITextField()
//    var searchDisplayController:UISearchDisplayController
    //展示列表
    var tableView: UITableView!
    
    //搜索控制器
    var countrySearchController = UISearchController()
    //搜索过滤后的结果集
    var searchArray:[SearchZixuanguData] = [SearchZixuanguData](){
        didSet{self.tableView.reloadData()}
    }
    var resultItems:[String]=[]
    var suggestItems:[String]=[]
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.countrySearchController.isActive {
            return self.searchArray.count
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
        -> UITableViewCell {
            //为了提供表格显示性能，已创建完成的单元需重复使用
            let identify:String = "SearchStockCell"
            //同一形式的单元格重复使用，在声明时已注册
            var cell = tableView.dequeueReusableCell(withIdentifier: identify,
                                                     for: indexPath) as! SearchStockTableViewCell
            if (cell == nil){
                cell = SearchStockTableViewCell(style: .default, reuseIdentifier: identify)
            }
            print(marketViewControllerDelegate)
            if self.countrySearchController.isActive {
                if (!searchArray.isEmpty){
                cell.codeLabel?.text = self.searchArray[indexPath.row].code
                cell.nameLabel?.text = self.searchArray[indexPath.row].name
                cell.pinyinLabel?.text = self.searchArray[indexPath.row].pinyin
                //        如果自选股的 codes 数组里面包含了，searchArray[indexPath.row].code，则应该为-，否则为+
                // 发送通知：
//                NotificationCenter.default.post(name: Notification.Name(rawValue: "kNotificationTestName"), object: "testContent")
                    cell.rightButton.code = self.searchArray[indexPath.row].code
                    if (marketViewControllerDelegate?.zixuangu.codes.contains(cell.codeLabel.text!))!{
                    cell.rightButton.status = .minus
                        cell.rightButton.setBackgroundImage(UIImage(named:"minusButton"), for: .normal)
                }else{
                    cell.rightButton.status = .plus
                    cell.rightButton.setBackgroundImage(UIImage(named:"plusButton"), for: .normal)
                }
                
                cell.rightButton.addTarget(self, action: #selector(clickCellButton(_:)), for: .touchUpInside)
                cell.rightButton.isEnabled = true
                cell.rightButton.isHidden = false
                
            }
            }
            return cell
    }
    
    @objc func clickCellButton(_ sender:CustomButton){
        switch (sender.status!) {
        case .plus:
            marketViewControllerDelegate?.zixuangu.codes.append(sender.code)
                    sender.status = .minus
                    sender.setBackgroundImage(UIImage(named:"plusButton"), for: .normal)
            tableView.reloadData()
        case .minus:
            let index = marketViewControllerDelegate?.zixuangu.codes.index(of: sender.code)
            marketViewControllerDelegate?.zixuangu.codes.remove(at: index!)
                    sender.status = .plus
                    sender.setBackgroundImage(UIImage(named:"minusButton"), for: .normal)
            tableView.reloadData()
        }
        

        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //跳到股票行情页面
        
        if(searchBar.isHidden == false){
            searchBar.isUserInteractionEnabled = false
            searchBar.isHidden = true
        }

        let stockDetailViewController = StockDetailViewController()//SearchStockViewController()
        let cell = tableView.cellForRow(at: indexPath) as! SearchStockTableViewCell
        stockDetailViewController.stockCode = cell.codeLabel?.text
//        searchStockViewController.navigationItem.title = "搜索股票"
        let stockDetailViewNavigationController = UINavigationController(rootViewController: stockDetailViewController)
        stockDetailViewNavigationController.navigationBar.titleTextAttributes = (naviBarTitleAttributes as! [NSAttributedStringKey : Any])
        
        //        防止重复弹出
        let viewController = UIApplication.shared.keyWindow?.rootViewController
        if let isNavigationController = viewController?.presentedViewController?.isKind(of: UINavigationController.self){
            if(isNavigationController == true){
                let navigation = viewController?.presentedViewController as! UINavigationController
                if(navigation.topViewController?.isKind(of: StockDetailViewController.self))!{
                    return
                }
            }
        }
//        这是原先避免重复跳转的写法，暂时改成直接跳转试试
        if((viewController?.presentedViewController) != nil){
            viewController?.presentedViewController?.dismiss(animated: false, completion: {
//                以下的 self 暂时不知道怎么改成 weakself
                /*viewController?.*/self.present(stockDetailViewNavigationController, animated: true, completion: nil)
            })
        }else{
            viewController?.present(stockDetailViewNavigationController, animated: true, completion: nil)
        }
//        viewController?.present(stockDetailViewNavigationController, animated: true, completion: nil)
        tableView.deselectRow(at: indexPath, animated: true)
        
        
        
//        navigationController?.pushViewController(stockDetailViewController, animated: true)
        
    }
    //实时进行搜索
    
    func updateSearchResults(for searchController: UISearchController) {
        //    self.searchArray = self.schoolArray.filter{ (school) -> Bool in
        //    re.turn school.contains(searchController.searchBar.text!)}
        
        
        weak var weakSelf:SearchStockViewController? = self
        let callBack:(([SearchZixuanguData]?)->(Void)) = { result in
            weakSelf?.searchArray = result!
            print(weakSelf?.searchArray)
        }
        Utils.AlamofireAsynchronousGETSearchZixuanguData(code: searchController.searchBar.text!, callBack: callBack)
//        searchController.searchBar.rx.text.orEmpty.asObservable().throttle(0.3, scheduler: MainScheduler.instance).subscribe(onNext: { (string) in
//            Utils.AlamofireAsynchronousGETSearchZixuanguData(code: string, callBack: callBack)
//        }, onError: { (error) in
//            print(error)
//        }, onCompleted: {
//            print("完成")
//        }) {
//            print("析构")
//        }
//        searchController.searchBar.rx.text.orEmpty.subscribe(onNext: { (string) in
//            Utils.AlamofireAsynchronousGETSearchZixuanguData(code: string, callBack: callBack)
//        }, onError: { (error) in
//            print(error)
//        }, onCompleted: {
//            print("完成了搜索")
//        }) {
//            print("完成了析构")
//        }
//        没有实现 rx 的搜索
//        searchController.searchBar.rx.text.orEmpty.subscribe(onNext: { (re) in
//            print(re)
//            Utils.AlamofireAsynchronousGETSearchZixuanguData(code: re, callBack: callBack)
//
//        }, onError: nil, onCompleted: nil, onDisposed: nil)
        
//        searchController.searchBar.rx.text.asObservable().throttle(0.3, scheduler: MainScheduler.instance).flatMapLatest { (query) -> ObservableConvertibleType in
//            Utils.AlamofireAsynchronousGETSearchZixuanguData(code: query!,callBack: callBack)
//        }
        
        
//        Utils.AlamofireAsynchronousGETSearchZixuanguData(code: searchBar.text!, callBack: callBack)
        
        
        
        
//            let searchResults = searchBar.rx.text.asDriver()
////                .throttle(0.3, scheduler: MainScheduler.instance)
//                .throttle(0.3)
//                .distinctUntilChanged({ (lhs, rhs) -> Bool in
//                    return lhs == rhs
//                })
////                .flatMapLatest { query -> Observable<[Repository]> in
//                .flatMapLatest { (thequery:String?) -> ObservableConvertibleType in
////                .flatMapLatest { (thequery) -> Observable<String> in
//                    guard let query = thequery else{return Observable.just([])}
//                    if query.isEmpty {
//                        return Observable.just([])
//                    }
        //修改 dosearchapi
//                    return doSearchAPI(query).retry(3)
//                    return Utils.AlamofireAsynchronousGETSearchZixuanguData(code: query, callBack: callBack).retry(2)
//                        .catchErrorJustReturn([])
//
//
//                esef
//                    .observeOn;(MainScheduler.instance)
    }
    func addCompleteButton(){
        //完成按钮所在的工具栏
        let inputComplete=UIToolbar(frame: CGRect(x: 0, y: 200, width: SCREEN_WIDTH, height: 40))
        inputComplete.isHidden = false
        inputComplete.backgroundColor = .red
//        inputComplete.sizeToFit()
        //工具栏上添加完成按钮
        let spaceBtn = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let closeItem=UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.done, target: self, action: (#selector(close)))
        inputComplete.items = [spaceBtn, closeItem]
        //完成附加在键盘上
//        let textField = searchBar.value(forKey: "searchField") as! UITextField
//        textField.inputAccessoryView = inputComplete
        searchBar.inputAccessoryView = inputComplete
        searchBar.inputAccessoryView?.isHidden = false
    }
    @objc func close(){
        if(searchBar.isFirstResponder==true){
            searchBar.resignFirstResponder()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //创建表视图
//        navigationController?.navigationBar.tintColor = .APP
        let tableViewFrame = CGRect(x: 0, y: 0, width: self.view.frame.width,
                                    height: self.view.frame.height-64)
        self.tableView = UITableView(frame: tableViewFrame, style:.plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        searchBar.delegate = self
        
        //创建一个重用的单元格
        self.tableView!.register(SearchStockTableViewCell.self,
                                 forCellReuseIdentifier: "SearchStockCell")
        self.view.addSubview(self.tableView!)
        
        
//        let tevi = UITextField(frame: CGRect(x: 0, y: 100, width: 375, height: 30))
//        view.addSubview(tevi)
//        tevi.rx.text.asObservable().subscribe { (result) in
//            print(result)
//        }
        
        //配置搜索控制器
        self.countrySearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self//两个样例使用不同的代理
            controller.hidesNavigationBarDuringPresentation = false
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.searchBarStyle = .minimal
            controller.searchBar.sizeToFit()
            self.tableView.tableHeaderView = controller.searchBar
//            self.tableView.tableHeaderView = tevi
            
            return controller
        })()
        addCompleteButton()
    }
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        print("1234567890")
        searchBar.becomeFirstResponder()
        return true
    }
    func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
        print("0987654321")
        return true
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print("textsssssss:\(searchText)")
        print("1aaaaasssssdddddd")
    }
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        print("zzzzzzzzzzzzzzzzzz")
    }
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        print("ssssssssssss")
    }

    override func viewWillAppear(_ animated: Bool) {
        navigationController?.navigationBar.setBackgroundColor(.APP)
        makeReturnButton()
    }
    func makeReturnButton(){
        let bki = UIBarButtonItem()
        let btn = UIButton(type: .custom)
        btn.tintColor = .white
        btn.setTitle(" < ", for: .normal)
        btn.addTarget(self, action: #selector(backNative), for: .touchUpInside)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.setTitleColor(.white, for: .normal)
        btn.sizeToFit()
        btn.contentHorizontalAlignment = .left
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
        btn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        bki.customView = btn
        navigationItem.leftBarButtonItem = bki
    }
    @objc func backNative(){
        navigationController?.dismiss(animated: true, completion: nil)
    }

        // Do any additional setup after loading the view.
    

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.tableView.reloadData()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
